package com.huo.importdata.service;

import com.huo.common.enumtype.FileTypeEnum;
import com.huo.common.enumtype.FtpFileStatusEnum;
import com.huo.common.enumtype.R;
import com.huo.filestransport.dao.FtpFileInfoDao;
import com.huo.filestransport.dao.FtpfilelogDao;
import com.huo.filestransport.entity.FtpFileInfoEntity;
import com.huo.filestransport.entity.Ftpfilelog;
import com.huo.filestransport.vo.FtpServerInfo;
import com.huo.importdata.dao.CallProcedureMapper;
import com.huo.util.DateUtils;
import com.huo.util.FtpUtil;
import com.huo.util.UncompressFileTAR;
import org.apache.commons.net.ftp.FTPClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

@Service
public class ImportDate {

    private final Logger logger = LoggerFactory.getLogger(getClass());

    @Autowired
    FtpServerInfo ftpServerInfo;
    @Autowired
    FtpFileInfoDao ftpFileInfoDao;
    @Autowired
    FtpUtil ftpUtil;
    @Autowired
    FtpfilelogDao ftpfilelogDao;
    @Autowired
    UncompressFileTAR uncompressFileTAR;
    @Autowired
    ImportDataCdfmService importDataCdfmService;
    @Autowired
    ImportDataCifmService importDataCifmService;
    @Autowired
    ImportDataCusService importDataCusService;
    @Autowired
    ImportDataDpfmService importDataDpfmService;
    @Autowired
    ImportDataEsfmService importDataEsfmService;
    @Autowired
    CallProcedureMapper callProcedureMapper;

    public String  importAlldate(String dataDate){

        try {
            if(dataDate == null || "".equals(dataDate)){
                dataDate = ftpFileInfoDao.selectCurrentData();
                if(dataDate == null || "".equals(dataDate)){
                    return "1";
                }
                Date currentDate = DateUtils.getDate(dataDate,"yyyyMMdd");
                if(currentDate.after( DateUtils.DateCount(ftpServerInfo.getDelayTime()))){
                    return "1";
                }
                dataDate = DateUtils.DateCount(currentDate,1,"yyyyMMdd");
            }

            logger.info("导入数据开始:{}",dataDate);

            ftpFileInfoDao.updateCurrentData(dataDate);

            initFtpfiles(dataDate);

            downloadFtpFileByDB(dataDate);

            unzip(dataDate);

            importFtpData(dataDate);

            logger.info("导入数据结束:{}",dataDate);

            logger.info("初始化数据开始:{}",dataDate);
            callProcedureMapper.initAllDate();
            logger.info("初始化数据结束:{}",dataDate);

            logger.info("积分计算开始:{}",dataDate);
            callProcedureMapper.consumeIntegral_all();
            logger.info("积分计算结束:{}",dataDate);
        } catch (Exception e) {
            e.printStackTrace();
            logger.info(e.getMessage(),e);
        }

        return "0";
    }




    public void initFtpfiles(String dataDate){
        List<String> list = ftpServerInfo.getFiles();
        String filsFix = ftpServerInfo.getFtpDirectory()+ dataDate + "/";
        for(String fileName : list){
            FtpFileInfoEntity fe = ftpFileInfoDao.selectByFtpFilePath(filsFix + fileName);
            if(fe == null){
                FtpFileInfoEntity record = new FtpFileInfoEntity();
                record.setFtpfilestatus(FtpFileStatusEnum.FTPFILE_STATUS_DOWNLOAD.getCode());
                record.setCreatetime(new Date());
                record.setFtpfilename(fileName);
                record.setFtpfilepath(filsFix + fileName);
                record.setDataDate(DateUtils.getDate(dataDate,"yyyyMMdd"));
                ftpFileInfoDao.insert(record);
            }
        }
    }


    public R downloadFtpFileByDB(String dataDate) {
        String localPath = ftpServerInfo.getLocalDirectory();
        logger.info("下载指定目录(DB)下的文件开始：" );
        FTPClient ftp = null;
        try {
            //对数据库进行查询，查询状态为1的数据
            FtpFileInfoEntity param = new FtpFileInfoEntity();
            param.setDataDateStr(dataDate);
            param.setFtpfilestatus(FtpFileStatusEnum.FTPFILE_STATUS_DOWNLOAD.getCode());
            List<FtpFileInfoEntity> ftpFileInfoEntityList = ftpFileInfoDao.selectByFtpFileStatusAndDatadate(param);
            if(ftpFileInfoEntityList != null && ftpFileInfoEntityList.size() > 0) {
                ftp = ftpUtil.getFTPConnection();
            }
            int fileNum = 0;
            for(FtpFileInfoEntity ffie : ftpFileInfoEntityList) {
                Date beginTime = new Date();
                R r = ftpUtil.downloadFtpFileByFtpPath(ffie.getFtpfilepath(),localPath,ftp);
                if(R.checkOK(r)) {
                    long filesize = (Long) r.get("filesize");
                    long createTime = (Long) r.get("createTime");
                    String localFile = (String) r.get("localFile");
                    //修改记录，将状态改为2
                    FtpFileInfoEntity record = new FtpFileInfoEntity();
                    record.setId(ffie.getId());
                    record.setUpdatetime(new Date());
                    record.setDownloadpath(localFile);
                    record.setFtpfilestatus(FtpFileStatusEnum.FTPFILE_STATUS_FISH.getCode());
                    record.setFtpfilesize(filesize);
                    record.setFtpfiledatetime(String.valueOf(createTime));
                    ftpFileInfoDao.updateByPrimaryKeySelective(record);
                    //记录日志
                    Ftpfilelog ftpfilelogRecord = new Ftpfilelog();
                    ftpfilelogRecord.setBegintime(beginTime);
                    ftpfilelogRecord.setEndtime(new Date());
                    ftpfilelogRecord.setFtpfiledatetime(ffie.getFtpfiledatetime());
                    ftpfilelogRecord.setFtpfilename(ffie.getFtpfilename());
                    ftpfilelogRecord.setFtpfilepath(ffie.getFtpfilepath());
                    ftpfilelogRecord.setFtpfilesize(ffie.getFtpfilesize());
                    ftpfilelogRecord.setFtplocalpath(localPath + ffie.getFtpfilepath());
                    ftpfilelogRecord.setFtpfiletype(FileTypeEnum.DOWNLOAD.getCode());
                    ftpfilelogDao.insert(ftpfilelogRecord);
                    fileNum ++ ;
                }
            }
            logger.info("下载指定目录(DB)下的文件结束："  + "下载的文件数量为：" + fileNum);
            return R.ok();
        } catch (Exception e) {
            logger.error(e.getMessage(),e);
            return R.error("下载指定目录(DB)的文件失败" );
        }finally {
            ftpUtil.closeFTPConnection(ftp);
        }
    }

    public void unzip(String dataDate){
        List<FtpFileInfoEntity> ftpFileInfoEntityList = ftpFileInfoDao.selectByFtpFileStatus(FtpFileStatusEnum.FTPFILE_STATUS_FISH.getCode());
        for(FtpFileInfoEntity ffe : ftpFileInfoEntityList){
            String filePath = uncompressFileTAR.unZipFile(ffe.getDownloadpath());
            FtpFileInfoEntity record = new FtpFileInfoEntity();
            record.setUnzipfilepath(filePath);
            record.setUpdatetime(new Date());
            record.setId(ffe.getId());
            record.setFtpfilestatus(FtpFileStatusEnum.FTPFIEL_STATUS_UNZIP.getCode());
            ftpFileInfoDao.updateByPrimaryKeySelective(record);
        }
    }

    private void importFtpData(String dataDate){
        importDataCdfmService.importCdfmByDate(dataDate);
        importDataCifmService.importCifm(dataDate);
        importDataCusService.importCus(dataDate);
        importDataDpfmService.importDpfm(dataDate);
        importDataEsfmService.importEsfm(dataDate);
    }
}
